﻿using System;
using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using SdmxMl.Common;
using SdmxMl.Manager;
using SdmxMl.Structure;

namespace SdmxMl.Pdf
{
    public class PdfArtefactGen
    {
        #region Internal members

        protected Document document;
        protected SmManager sm;
        protected Dictionary<string, CodeListType> dicoCodelist;
        protected RefVarHelper varHelper;
        protected PdfVarDetail pdfVar;
        protected Artefact targetArtefact;

        #endregion

        public PdfArtefactGen(string docPath, SmManager smMgr, SdmxArtefactType arType, string artefactFullId, string lang)
        {
            dicoCodelist = new Dictionary<string, CodeListType>();
            sm = smMgr;

            // Load Artefact MSD from registry
            ArtefactRefTyped art = new ArtefactRefTyped(arType, artefactFullId);
            sm.LoadMissingArtefactsFromRegistry(new ArtefactRefTypedList(art));
            targetArtefact = sm.GetArtefact(art);
            if (targetArtefact == null)
                throw new ApplicationException("Artefact not found: " + artefactFullId);

            //Create PDF Document
            document = new Document(PageSize.A4);
            document.SetMargins(72, 72, 72, 72);
            document.SetMarginMirroring(true);

            // Create helper for codelist and concepts
            varHelper = new RefVarHelper(sm);
            pdfVar = new PdfVarDetail(document, lang, PageSize.A4, varHelper);
            try
            {

                // we create a writer that listens to the document
                // and directs a PDF-stream to a file
                PdfWriter docWriter = PdfWriter.GetInstance(document, new FileStream(docPath, FileMode.Create));
                PdfWriterEvents writerEvent = new PdfWriterEvents("Test");
                docWriter.PageEvent = writerEvent;
                PdfWriterPage page = new PdfWriterPage(targetArtefact.AgencyId);
                docWriter.PageEvent = page;

                // open the document
                document.Open();

                FontSelector selector = new FontSelector();
                selector.AddFont(FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9));
            }
            catch
            {
                document.Close();
                throw;
            }
        }

    }
}
